package org.xnat.xnatfs.asset;

import org.apache.log4j.Logger;
import org.xnat.xnatfs.cache.CacheProvider;
import org.xnat.xnatfs.cache.CacheUtils;
import org.xnat.xnatfs.cache.ICache;
import org.xnat.xnatfs.exception.RequestException;

import com.bradmcevoy.http.Auth;

public class CachingAssetProvider implements IAssetProvider {
  private final static Logger logger = Logger.getLogger ( CachingAssetProvider.class );

  private AssetProvider assetProvider;
  private ICache cache;

  public CachingAssetProvider () {
    assetProvider = new AssetProvider ();
    cache = CacheProvider.createCache ( "ShortTerm" );
  }

  @Override
  public IStringAsset getStringAsset ( String url, Auth auth ) throws RequestException {
    String key = CacheUtils.createKey ( auth, "StringAsset", url );

    IStringAsset asset = (IStringAsset) getCachedAsset ( key );
    if ( asset == null ) {
      logger.debug ( "Key not in cache for url: " + url );
      asset = assetProvider.getStringAsset ( url, auth );
      cache.put ( key, asset );
    }
    return asset;
  }

  @Override
  public IAsset getAssetHead ( String url, Auth auth ) throws RequestException {
    String key = CacheUtils.createKey ( auth, "AssetHead", url );

    IAsset asset = getCachedAsset ( key );
    if ( asset == null ) {
      logger.debug ( "Key, " + key + ", not in cache for url: " + url );
      asset = assetProvider.getAssetHead ( url, auth );
      cache.put ( key, asset );
    }
    return asset;
  }

  // FIXME implement caching
  @Override
  public IStreamAsset getStreamAsset ( String url, Auth auth ) throws RequestException {
    return assetProvider.getStreamAsset ( url, auth );
  }

  private IAsset getCachedAsset ( String key ) {
    if ( cache.get ( key ) != null ) {
      logger.debug ( "Key, " + key + " in cache" );
      return (IAsset) cache.get ( key );
    }
    return null;
  }
}
